package cn.chiship.sdk.core.util;

import com.alibaba.fastjson.JSON;

/**
 * @author lijian 输出打印工具
 */
public class PrintUtil {

	private PrintUtil() {

	}

	/**
	 * 控制台打印
	 * @param value 内容
	 */
	public static void console(Object value) {
		StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
		StackTraceElement callerElement = stackTrace[1];
		if (stackTrace.length > 2) {
			callerElement = stackTrace[2];
		}
		format(callerElement, null, value);

	}

	/**
	 * 控制台打印
	 * @param title 标题
	 * @param value 内容
	 */
	public static void console(String title, Object value) {
		StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
		StackTraceElement callerElement = stackTrace[2];
		if (stackTrace.length > 3) {
			callerElement = stackTrace[3];
		}
		format(callerElement, title, value);

	}

	/**
	 * 格式化输出
	 * @param callerElement 栈对象
	 * @param title 标题
	 * @param value 内容
	 */
	private static void format(StackTraceElement callerElement, String title, Object value) {
		String methodName = callerElement.getClassName() + "." + callerElement.getMethodName();
		if (ObjectUtil.isEmpty(callerElement)) {
			System.out.println("*****************************************" + DateUtils.getTime()
					+ "*****************************************");
		}
		else {
			System.out.println(String.format("%s\t\033[32m%s\033[0m\t第\033[31m(%d)\033[0m行打印信息如下：", DateUtils.getTime(),
					methodName, callerElement.getLineNumber()));
		}
		if (!StringUtil.isNullOrEmpty(title)) {
			System.out.println(
					"*****************************************" + title + "*****************************************");
		}
		System.out.println("\t\033[34m" + JSON.toJSONString(value) + "\033[0m\n");

	}

}
